package excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;


public class WriteExcel {

	public void writeListEmInfo(Integer hangBatDau,Vector<Vector<String>> duLieu,Integer cotBatDau,String linkTemplate) {
		
		JFileChooser fileChooser = new JFileChooser(".");
	    FileFilter filter1 = new ExtensionFileFilter("Excel file", new String[] { "XLS", "XLSX" });
	    fileChooser.setFileFilter(filter1);
	    int status = fileChooser.showSaveDialog(null);
	    if (status == JFileChooser.APPROVE_OPTION) {
	    	File selectedFile = fileChooser.getSelectedFile();
		    String path = selectedFile.getPath();
			POIFSFileSystem fs = null;
			try {
				fs = new POIFSFileSystem(new FileInputStream(linkTemplate));
				HSSFWorkbook wb;
				wb = new  HSSFWorkbook(fs);
				HSSFSheet sheet = wb.getSheetAt(0); 
		
				for (int i = 0; i < duLieu.size(); i++) {
					int a = hangBatDau +i;
					for (int j = 0; j < duLieu.get(i).size(); j++) {
						int b = cotBatDau +j;
						HSSFRow row = sheet.getRow(a);
					    Cell cell = row.getCell(b);
					    cell.setCellType(Cell.CELL_TYPE_STRING);
					    cell.setCellValue(duLieu.get(i).get(j).toString());
					}
				}
			sheet.autoSizeColumn((short)0); 
			sheet.autoSizeColumn((short)1); 
			sheet.autoSizeColumn((short)2);
			sheet.autoSizeColumn((short)3);
			sheet.autoSizeColumn((short)4);
			sheet.autoSizeColumn((short)5);
			sheet.autoSizeColumn((short)6);
			sheet.autoSizeColumn((short)7);
		
			//Sheet sheet1 = wb.createSheet("new sheet");
			FileOutputStream fileOut;
			fileOut = new FileOutputStream(path+".xls");
			wb.write(fileOut);
			fileOut.close();
			} catch (Exception e) {
				e.printStackTrace();
			} 				
	    }else if (status == JFileChooser.CANCEL_OPTION) {
	    	System.out.println(JFileChooser.CANCEL_OPTION);
	    }
	}

}

